﻿
using LS.FrmUI.Dal;
using LS.FrmUI.Model;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Printing;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Windows.Forms;

namespace LS.FrmUI
{
    public partial class FrmChartOutPut : Form
    {
        AttDal attDal = new AttDal();
        AreaDal areaDal = new AreaDal();
        List<Attachment> listDataSouse = new List<Attachment>();//每次从DB中获取的筛选后的结果
        List<Attachment> tempDataSouse = new List<Attachment>();//要打印的结果
        string printTipStr = string.Empty;//打印下面的提示。
        public FrmChartOutPut()
        {
            this.SetStyle(ControlStyles.OptimizedDoubleBuffer | ControlStyles.ResizeRedraw | ControlStyles.AllPaintingInWmPaint, true);
            this.UpdateStyles();

            InitializeComponent();

            //利用反射设置DataGridView的双缓冲
            Type dgvType = this.dataGridView1.GetType();
            PropertyInfo pi = dgvType.GetProperty("DoubleBuffered",
                BindingFlags.Instance | BindingFlags.NonPublic);
            pi.SetValue(this.dataGridView1, true, null);

            cboArea.Items.Add("ALL");
            cboArea.Items.AddRange(areaDal.GetAllArea().ToArray());
            cboArea.Items.Add("其他");

            SysSettingDal dal = new SysSettingDal();
            DataTable printTip = dal.GetDTFromSysSetting();
            try
            {
                printTipStr = Convert.ToString(printTip.Rows[0]["printTip"]);
            }
            catch
            {
                printTipStr = "请认真核对后签字回传照片,疑问电话:0371-89917819";
            }
        }
        private void cboArea_TextUpdate(object sender, EventArgs e)
        {
            cboArea.Items.Clear();
            string tempAdd = string.Empty;
            cboArea.Items.Add("ALL");

            List<string> relList = areaDal.GetAllArea();
            relList.ForEach(x =>
            {
                if (!string.IsNullOrEmpty(x))
                {
                    if (x.Contains(cboArea.Text))
                    {
                        cboArea.Items.Add(x);
                    }
                }
            });
            cboArea.Items.Add("其他");
            cboArea.SelectionStart = cboArea.Text.Length;
            Cursor = Cursors.Default;
            cboArea.DroppedDown = true;
        }
        private void FullDataGridView()
        {
            listDataSouse = attDal.GetResByAddress(cboArea.Text);
            listDataSouse = (from p in listDataSouse
                             select p).OrderBy(m => m.Sort).ThenBy(s=>s.JName).ToList();//排序，对应导入到DB的sort

            this.dataGridView1.DataSource = listDataSouse;
            lblCount.Text = "查询行数值:" + listDataSouse.Count.ToString();
            lblIndex.Text = "地区索引值:" + cboArea.SelectedIndex.ToString();
            int needPrintCount = listDataSouse.Count;
            if (needPrintCount == 0)
            {
                lblTipsNum.Text = "0";
            }
            if (needPrintCount % 45 == 0)
            {
                lblTipsNum.Text = (needPrintCount / 45 ).ToString();
            }
            else
            {
                lblTipsNum.Text = (needPrintCount / 45+1).ToString();
            }
            //else
            //{
            //    lblTipsNum.Text = (listDataSouse.Count / 45+1).ToString();
            //}
            setting.WLAdd = cboArea.Text;//提示用户打印哪个地区
            IsFirstPrint = false;//不是第一次打印
        }
        private void button1_Click(object sender, EventArgs e)
        {
            FullDataGridView();
        }

        private void cboArea_SelectedIndexChanged(object sender, EventArgs e)
        {
            FullDataGridView();
        }

        private void FrmChartOutPut_Load(object sender, EventArgs e)
        {
            this.dataGridView1.AutoGenerateColumns = false;
            this.dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            this.dataGridView1.ReadOnly = true;
            this.cboArea.SelectedIndex = 0;
        }
        //手动打印
        private void btnPriviewCharts_Click(object sender, EventArgs e)
        {
            string pngFile = Path.Combine(Application.StartupPath, "自动打印保存数据");
            if (!Directory.Exists(pngFile))
            {
                Directory.CreateDirectory(pngFile);
            }

            if (listDataSouse.Count == 0)
            {
                MessageBox.Show("无数据，无法打印");
                return;
            }
            if (cboArea.Text=="ALL")
            {
                MessageBox.Show("手动打印模式不可打印ALL地区");
                return;
            }
            IsFirstPrint = true;//刚选的结果，假装没打印
            currentPrintIndex = 1;

            PrintDocument printDocument1 = new PrintDocument();
            printDocument1.DefaultPageSettings.PaperSize = new PaperSize("CustomPaperSize", pWidth, pHeigth);
            printDocument1.DefaultPageSettings.Landscape = false;//纵向
            printDocument1.PrintController = new System.Drawing.Printing.StandardPrintController();//隐藏正在打印...
            printDocument1.PrintPage += new PrintPageEventHandler(this.PrintDocument_PrintPage);
            PrintPreviewDialog printPreviewDialog1 = new PrintPreviewDialog();
            printPreviewDialog1.Document = printDocument1;
           
            // DialogResult result = printPreviewDialog1.ShowDialog();
            printDocument1.Print();//开始打印 
            //if (result == System.Windows.Forms.DialogResult.OK)
            //{
            //    printDocument1.Print();//开始打印 
            //}
        }
        int pWidth = 827;
        int pHeigth = 1169;
        int currentPrintIndex = 1;//当前页
        int allPrintCount = 0;//总页数
        int hasCount = 45;//每页显示多少个
        bool IsFirstPrint = true;
        //打印方法
        private void PrintDocument_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
        {
            if (IsFirstPrint)
            {
                setting.WLAdd = cboArea.Text;
                new FrmWLID().ShowDialog();
            }
            if (setting.WLID == "结束打印")//如果等于结束打印则停止
            {
                return;
            }
            //获取总页数
            allPrintCount = listDataSouse.Count % hasCount == 0 ? listDataSouse.Count / hasCount : listDataSouse.Count / hasCount + 1;
           
            int rowYsize = 25;//每个表格之间的空余间隔

            Image img = new System.Drawing.Bitmap(pWidth, pHeigth);

            Graphics gSave = Graphics.FromImage(img);
            gSave.FillRectangle(Brushes.White,0,0,pWidth,pHeigth);//底色填充白色

            tempDataSouse = listDataSouse.Skip((currentPrintIndex - 1) * hasCount).Take(hasCount).ToList();//分页

            string fifterPath = Path.Combine(Application.StartupPath, "System.Data.Words.dll");//过滤字判断

            List<string> words = File.ReadAllLines(fifterPath).ToList().Distinct().ToList();



            #region 画表头
            System.Drawing.Font fFont = new System.Drawing.Font(new FontFamily("宋体"), 12);//大字字体。
            System.Drawing.Font contentFont = new System.Drawing.Font(new FontFamily("宋体"), 10);//小字字体。
            e.Graphics.DrawString(" ", new System.Drawing.Font(new FontFamily("宋体"), 30), Brushes.Black, 100, 0);
            e.Graphics.DrawString("售后:" + cboArea.Text + " 物流单号:" + setting.WLID, new System.Drawing.Font(new FontFamily("宋体"), 24), Brushes.Black, 200, 5);
            e.Graphics.DrawLine(new Pen(Color.Gray), new Point(0, 38), new Point(827, 38));
            e.Graphics.DrawString("工单", fFont, Brushes.Black, 10, 45);//
            e.Graphics.DrawString("送修人", fFont, Brushes.Black, 160, 45);//
            e.Graphics.DrawString("手机", fFont, Brushes.Black, 225, 45);//
            e.Graphics.DrawString("型号", fFont, Brushes.Black, 325, 45);//
            e.Graphics.DrawString("条码", fFont, Brushes.Black, 410, 45);//ISN
            e.Graphics.DrawString("报修日期", fFont, Brushes.Black, 510 + 20, 45);//
            e.Graphics.DrawString("金额", fFont, Brushes.Black, 610, 45);//
            e.Graphics.DrawString("经销商姓名", fFont, Brushes.Black, 655, 45);//
            e.Graphics.DrawLine(new Pen(Color.Gray), new Point(0, 65), new Point(827, 65));
                /*保存图片*/
            gSave.DrawString(" ", new System.Drawing.Font(new FontFamily("宋体"), 30), Brushes.Black, 100, 0);
            gSave.DrawString("售后:" + cboArea.Text + " 物流单号:" + setting.WLID, new System.Drawing.Font(new FontFamily("宋体"), 24), Brushes.Black, 200, 5);
                gSave.DrawLine(new Pen(Color.Gray), new Point(0, 38), new Point(827, 38));
                gSave.DrawString("工单", fFont, Brushes.Black, 10, 45);//
                gSave.DrawString("送修人", fFont, Brushes.Black, 160, 45);//
                gSave.DrawString("手机", fFont, Brushes.Black, 225, 45);//
                gSave.DrawString("型号", fFont, Brushes.Black, 325, 45);//
                gSave.DrawString("条码", fFont, Brushes.Black, 410, 45);//ISN
                gSave.DrawString("报修日期", fFont, Brushes.Black, 510 + 20, 45);//
                gSave.DrawString("金额", fFont, Brushes.Black, 610, 45);//
                gSave.DrawString("经销商姓名", fFont, Brushes.Black, 655, 45);//
                gSave.DrawLine(new Pen(Color.Gray), new Point(0, 65), new Point(827, 65));
                /*保存图片*/
            #endregion
            #region 画表格
            foreach (var info in tempDataSouse)
            {
                string jname = (from w in words where info.JName.StartsWith(w) select w).FirstOrDefault();

                if (!string.IsNullOrEmpty(jname))
                {
                  info.JName= info.JName.Replace(jname, "");
                }
                
                if (info.CName.Length>4)
                {
                    info.CName = info.CName.Substring(0, 4);
                }

                e.Graphics.DrawString(info.KITID, contentFont, Brushes.Black, 10, 45 + rowYsize);
                e.Graphics.DrawString(info.CName, contentFont, Brushes.Black,160, 45 + rowYsize);
                e.Graphics.DrawString(info.CPhone, contentFont, Brushes.Black, 225, 45 + rowYsize);
                e.Graphics.DrawString(info.PType, contentFont, Brushes.Black, 325, 45 + rowYsize);//
                e.Graphics.DrawString(info.ISN, contentFont, Brushes.Black, 410, 45 + rowYsize);
                /*保存图片开始*/
                gSave.DrawString(info.KITID, contentFont, Brushes.Black, 10, 45 + rowYsize);
                gSave.DrawString(info.CName, contentFont, Brushes.Black, 160, 45 + rowYsize);
                gSave.DrawString(info.CPhone, contentFont, Brushes.Black, 225, 45 + rowYsize);
                gSave.DrawString(info.PType, contentFont, Brushes.Black, 325, 45 + rowYsize);
                gSave.DrawString(info.ISN, contentFont, Brushes.Black, 410, 45 + rowYsize);
                /*保存图片结束*/
                if (!string.IsNullOrEmpty(Convert.ToString(info.DateTime)))
                {
                    e.Graphics.DrawString(info.DateTime.ToString("yyyy-MM-dd"), contentFont, Brushes.Black, 510 + 20, 45 + rowYsize);
                    gSave.DrawString(info.DateTime.ToString("yyyy-MM-dd"), contentFont, Brushes.Black, 510 + 20, 45 + rowYsize);
                }

                if (info.allMoney != 0)
                {
                    e.Graphics.DrawString(Convert.ToString(info.allMoney), contentFont, Brushes.Black,610, 45 + rowYsize);
                    /*保存图片*/
                    gSave.DrawString(Convert.ToString(info.allMoney), contentFont, Brushes.Black,610, 45 + rowYsize);
                    /*保存图片*/
                }

                e.Graphics.DrawString(info.JName, contentFont, Brushes.Black, 655, 45 + rowYsize);
                /*保存图片*/
                gSave.DrawString(info.JName, contentFont, Brushes.Black, 655, 45 + rowYsize);
                /*保存图片*/
               
                rowYsize += 22;
            }
            #endregion
            #region 画底部
            e.Graphics.DrawString(System.DateTime.Now.ToString("yyyy年MM月dd日"), fFont, Brushes.Blue, 10, 1120);//表头 y 45 位置。
            e.Graphics.DrawString(printTipStr, fFont, Brushes.Red, 150, 1120);//表头 y 45 位置。
            e.Graphics.DrawString("当前" + currentPrintIndex + "页,共" + allPrintCount + "页,"+tempDataSouse.Count+"条", fFont, Brushes.Blue, 630, 1120);//表头 y 45 位置。
                /*保存图片*/
                gSave.DrawString(System.DateTime.Now.ToString("yyyy年MM月dd日"), fFont, Brushes.Blue, 10, 1120);//表头 y 45 位置。
                gSave.DrawString(printTipStr, fFont, Brushes.Red, 150, 1120);//表头 y 45 位置。
                gSave.DrawString("当前" + currentPrintIndex + "页,共" + allPrintCount + "页," + tempDataSouse.Count + "条", fFont, Brushes.Blue, 630, 1120);//表头 y 45 位置。
                /*保存图片*/
            #endregion

            /*打印完成的同时保存一张图片*/
            string pngFile = Path.Combine(Application.StartupPath, "自动打印保存数据");
            img.Save(Path.Combine(pngFile, cboArea.Text + "【" + currentPrintIndex + "-" + allPrintCount + "】" + System.DateTime.Now.ToString("yyyy_MM_dd HH_mm_ss") + ".png"));
            /*打印完成的同时保存一张图片*/

            currentPrintIndex++;//本次打印结束，下一页

            IsFirstPrint = false;
            if (currentPrintIndex > allPrintCount)
            {
                e.HasMorePages = false;  //关掉多页打印属性
                currentPrintIndex = 1;//当前页
            }
            else
            {
                e.HasMorePages = true;
            }
        }
        //自动打印
        private void btnOneKeyToPrint_Click(object sender, EventArgs e)
        {
            string pngFile = Path.Combine(Application.StartupPath, "自动打印保存数据");
            if (!Directory.Exists(pngFile))
            {
                Directory.CreateDirectory(pngFile);
            }
            currentPrintIndex = 1;
            for (int i = cboArea.SelectedIndex; i < cboArea.Items.Count; i++)
            {
                if (cboArea.SelectedIndex < cboArea.Items.Count - 1)
                {
                    cboArea.SelectedIndex += 1;

                    if (dataGridView1.RowCount <= 0)
                    {
                        continue;//如果没有数据就跳过。
                    }
                    new FrmWLID().ShowDialog();
                    if (setting.WLID == "结束打印")//如果等于结束打印则停止
                    {
                        break;
                    }
                    PrintDocument printDocument1 = new PrintDocument();
                    printDocument1.DefaultPageSettings.PaperSize = new PaperSize("CustomPaperSize", pWidth, pHeigth);
                    printDocument1.DefaultPageSettings.Landscape = false;//纵向
                    printDocument1.PrintController = new System.Drawing.Printing.StandardPrintController();//隐藏正在打印...
                    printDocument1.PrintPage += new PrintPageEventHandler(this.PrintDocument_PrintPage);
                    PrintPreviewDialog printPreviewDialog1 = new PrintPreviewDialog();
                    printPreviewDialog1.Document = printDocument1;
                    printDocument1.Print();//开始打印 
                }
            }
        }
        //导出Excel
        private void btnOutPutExcel_Click(object sender, EventArgs e)
        {
            if (dataGridView1.RowCount <= 0)
            {
                MessageBox.Show("无数据，无法导出。");
                return;
            }
            ExportExcels(cboArea.Text + "_" + System.DateTime.Now.ToString("yyyy年MM月dd日HH时mm分ss秒"), dataGridView1);
        }
        private void ExportExcels(string fileName, DataGridView myDGV)
        {
            string saveFileName = "";
            SaveFileDialog saveDialog = new SaveFileDialog();
            saveDialog.DefaultExt = "xls";
            saveDialog.Filter = "Excel文件|*.xls";
            saveDialog.FileName = fileName;
            saveDialog.ShowDialog();
            saveFileName = saveDialog.FileName;
            if (saveFileName.IndexOf(":") < 0) return; //被点了取消
            Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
            if (xlApp == null)
            {
                MessageBox.Show("无法创建Excel对象，可能您的机子未安装Excel");
                return;
            }
            Microsoft.Office.Interop.Excel.Workbooks workbooks = xlApp.Workbooks;
            Microsoft.Office.Interop.Excel.Workbook workbook = workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet);
            Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[1];//取得sheet1
            //写入标题
            for (int i = 0; i < myDGV.ColumnCount; i++)
            {
                worksheet.Cells[1, i + 1] = myDGV.Columns[i].HeaderText;
            }
            //写入数值
            for (int r = 0; r < myDGV.Rows.Count; r++)
            {
                for (int i = 0; i < myDGV.ColumnCount; i++)
                {
                    worksheet.Cells[r + 2, i + 1] = myDGV.Rows[r].Cells[i].Value;
                }
                System.Windows.Forms.Application.DoEvents();
            }
            worksheet.Columns.EntireColumn.AutoFit();//列宽自适应
            if (saveFileName != "")
            {
                try
                {
                    workbook.Saved = true;
                    workbook.SaveCopyAs(saveFileName);
                }
                catch (Exception ex)
                {
                    MessageBox.Show("导出文件时出错,文件可能正被打开！\n" + ex.Message);
                }
            }
            xlApp.Quit();
            GC.Collect();//强行销毁
            MessageBox.Show("文件： " + fileName + ".xls 保存成功", "信息提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
        public static bool DataTableToTxt(DataGridView gridview, string fileName, char strSplit)
        {
            if (gridview == null || gridview.Rows.Count == 0)
                return false;
            string filename = fileName;
            FileStream fileStream = new FileStream(filename, FileMode.OpenOrCreate);
            StreamWriter streamWriter = new StreamWriter(fileStream, System.Text.Encoding.UTF8);

            StringBuilder strBuilder = new StringBuilder();

            try
            {
                for (int i = 0; i < gridview.Rows.Count; i++)
                {
                    strBuilder = new StringBuilder();
                    for (int j = 0; j < gridview.Columns.Count; j++)
                    {
                        strBuilder.Append(gridview.Rows[i].Cells[j].Value.ToString() + strSplit);
                    }
                    //strBuilder.Remove(strBuilder.Length - 1, 1); // 将最后添加的一个strSplit删除掉
                    streamWriter.WriteLine(strBuilder.ToString());
                }
            }
            catch (Exception ex)
            {
                string strErrorMessage = ex.Message;
                return false;
            }
            finally
            {
                streamWriter.Close();
                fileStream.Close();
            }

            return true;
        }

        private void btnPrintHistory_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            string txtPath = Path.Combine(Application.StartupPath, "自动打印保存数据");
            if (!Directory.Exists(txtPath))
            {
                Directory.CreateDirectory(txtPath);
            }
            System.Diagnostics.Process.Start(txtPath);
        }

        private void dataGridView1_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            SolidBrush b = new SolidBrush(this.dataGridView1.RowHeadersDefaultCellStyle.ForeColor);
            e.Graphics.DrawString((e.RowIndex + 1).ToString(System.Globalization.CultureInfo.CurrentUICulture), this.dataGridView1.DefaultCellStyle.Font, b, e.RowBounds.Location.X + 20, e.RowBounds.Location.Y + 4);
        }
        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void FrmChartOutPut_FormClosing(object sender, FormClosingEventArgs e)
        {
            new FrmMain().Show();
        }

      

    }
}
